package com.fireXXX.job.analysis.crawler.common;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class CrawlerThreadPool extends Thread {

    private LinkedBlockingQueue queue = null;
    private ThreadPoolExecutor executor = null;

    private int threadNum = 1;
    private int queueSize = 1;

    public CrawlerThreadPool() {
        queue = new LinkedBlockingQueue<>(queueSize);
        executor = new ThreadPoolExecutor(threadNum, threadNum, 0L, TimeUnit.MILLISECONDS, queue);
    }

    public Future<?> submit(Runnable runnable) {
        return executor.submit(runnable);
    }

    @Override
    public void run() {
        while (true) {
            try {
                print();

                Thread.sleep(10000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void print() {
        if (executor.getActiveCount() > 0) {
            log.info("爬虫队列活跃线程数:{},队列大小:{}", executor.getActiveCount(), queue.size());
        }
    }

}
